import { validateIdCard, isMobile } from '@/utils/validate.js'
import { getDictDataByCode } from '@/api/auth/dict.js'

const validateHttp = (rule, value, callback) => {
  const url = /(http|https):\/\/([\w.]+\/?)\S*/
  if (!url.test(value)) {
    callback(new Error("输入正确的url地址"))
  } else {
    callback()
  }
}
// 密码验证
const validatePassword = (rule, value, callback) => {
  const password = /^(?!bai[0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$)^.{8,16}$/
  if (!password.test(value)) {
    callback(new Error('密码至少包括大写字母小写字及数字'))
  } else {
    callback()
  }
}

// 验证身份证号
let validateCardno = function (rules, value, callback) {
  let flag = validateIdCard(value)
  if (!flag) {
    return callback(new Error('请填写正确的证件号码'))
  } else {
    callback()
  }
}

// 验证整数
let checkNum = (rule, value, callback) => {
  if (value % 1 !== 0) {
    callback(new Error('请输入正确的年龄'))
  } else {
    if (value < 0) {
      callback(new Error('年龄不能为负'))
    } else {
      callback()
    }
  }
}

// 验证手机号
let checkPhoneNum = (rule, value, callback) => {
  if (!isMobile(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

// 验证时间
let checkTime = (rule, value, callback) => {
  let nowtime = new Date().getTime()
  let time = Date.parse(strToDate(value))
  if (time > nowtime) {
    callback(new Error('不能大于当前时间'))
  } else {
    callback()
  }
}

//空判断，也可以用underscore的_.isEmpty()函数
function isEmpty(fData) {
  if (typeof fData == "function") {
    return false;
  }
  return typeof fData == "undefined" || fData == undefined || fData == null ||
    fData.length == 0 || fData == 'null' || (fData != false && fData == '')
}

// null 判断
function isNull(fData, replaceData) {
  return isEmpty(fData) ? replaceData : fData;
}

// IE 下获取某个时间的时间戳
function strToDate(str) {
  if (isEmpty(str)) {
    return null
  }
  var converted = Date.parse(str)
  var myDate = new Date(converted)
  if (isNaN(myDate)) {
    if (str.indexOf(":") != -1) {
      str = str.replace(" ", "-")
      str = str.replace(":", "-")
      str = str.replace(":", "-") // 第二个时间
      var arys = str.split('-')
      myDate = new Date(arys[0], --arys[1], arys[2], isNull(arys[3], 0),
        isNull(arys[4], 0), isNull(arys[5], 0));
    } else {
      var arys = str.split('-')
      myDate = new Date(arys[0], --arys[1], arys[2])
    }
  }
  return myDate
}


/**
 * 验证科室
 */
let checkDepart = (rule, value, callback) => {
  if (value === '请选择科室') {
    callback(new Error('请选择科室'))
  } else {
    callback()
  }
}

/**
 * 根据编码获取数据字典数据
 */
async function getDictByCode (dictData = [], code) {
  dictData = await getDictDataByCode(code).then(res => {
    return res.data
  })
  return dictData
}

export {
  validateHttp,
  validatePassword,
  validateCardno,
  checkNum,
  checkPhoneNum,
  checkTime,
  getDictByCode,
  checkDepart
}
